"""
日志配置模块
"""

import logging
import logging.handlers
import sys
from pathlib import Path
from typing import Optional

from ..core.config import settings

def setup_logging(
    log_level: str = "INFO",
    log_file: Optional[Path] = None,
    log_format: Optional[str] = None
) -> logging.Logger:
    """设置应用日志"""
    
    # 确保日志目录存在
    settings.LOGS_DIR.mkdir(parents=True, exist_ok=True)
    
    # 默认日志格式
    if log_format is None:
        log_format = (
            "%(asctime)s - %(name)s - %(levelname)s - "
            "[%(filename)s:%(lineno)d] - %(message)s"
        )
    
    # 创建格式器
    formatter = logging.Formatter(log_format)
    
    # 获取根日志器
    root_logger = logging.getLogger()
    root_logger.setLevel(getattr(logging, log_level.upper()))
    
    # 清除现有处理器
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)
    
    # 文件处理器
    if log_file is None:
        log_file = settings.LOGS_DIR / "dialogue_service.log"
    
    # 使用轮转文件处理器
    file_handler = logging.handlers.RotatingFileHandler(
        log_file,
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    file_handler.setLevel(getattr(logging, log_level.upper()))
    file_handler.setFormatter(formatter)
    root_logger.addHandler(file_handler)
    
    # 错误日志文件处理器
    error_log_file = settings.LOGS_DIR / "dialogue_service_error.log"
    error_handler = logging.handlers.RotatingFileHandler(
        error_log_file,
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=3,
        encoding='utf-8'
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(formatter)
    root_logger.addHandler(error_handler)
    
    # 设置第三方库日志级别
    logging.getLogger("uvicorn").setLevel(logging.WARNING)
    logging.getLogger("fastapi").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)
    
    logger = logging.getLogger(__name__)
    logger.info(f"日志系统初始化完成，级别: {log_level}")
    logger.info(f"日志文件: {log_file}")
    
    return root_logger

def get_task_logger(task_id: str) -> logging.Logger:
    """获取任务专用日志器"""
    logger_name = f"task.{task_id}"
    task_logger = logging.getLogger(logger_name)
    
    # 如果已经配置过，直接返回
    if task_logger.handlers:
        return task_logger
    
    # 设置任务专用日志文件
    task_log_file = settings.LOGS_DIR / f"task_{task_id}.log"
    
    # 创建文件处理器
    file_handler = logging.FileHandler(task_log_file, encoding='utf-8')
    file_handler.setLevel(logging.INFO)
    
    formatter = logging.Formatter(
        "%(asctime)s - %(levelname)s - %(message)s"
    )
    file_handler.setFormatter(formatter)
    
    task_logger.addHandler(file_handler)
    task_logger.setLevel(logging.INFO)
    
    # 防止日志传播到根日志器，避免重复记录
    task_logger.propagate = False
    
    task_logger.info(f"任务日志器创建: {task_id}")
    return task_logger

class TaskLoggerAdapter(logging.LoggerAdapter):
    """任务日志适配器，自动添加任务ID到日志消息"""
    
    def __init__(self, logger: logging.Logger, task_id: str):
        super().__init__(logger, {"task_id": task_id})
    
    def process(self, msg, kwargs):
        return f"[Task {self.extra['task_id']}] {msg}", kwargs

def setup_task_logging(task_id: str) -> TaskLoggerAdapter:
    """设置任务日志记录"""
    task_logger = get_task_logger(task_id)
    return TaskLoggerAdapter(task_logger, task_id)

# 性能日志器
def get_performance_logger() -> logging.Logger:
    """获取性能日志器"""
    perf_logger = logging.getLogger("performance")
    
    if perf_logger.handlers:
        return perf_logger
    
    # 性能日志文件
    perf_log_file = settings.LOGS_DIR / "performance.log"
    
    file_handler = logging.handlers.RotatingFileHandler(
        perf_log_file,
        maxBytes=5 * 1024 * 1024,  # 5MB
        backupCount=3,
        encoding='utf-8'
    )
    
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(message)s"
    )
    file_handler.setFormatter(formatter)
    
    perf_logger.addHandler(file_handler)
    perf_logger.setLevel(logging.INFO)
    perf_logger.propagate = False
    
    return perf_logger

# 安全日志器
def get_security_logger() -> logging.Logger:
    """获取安全日志器"""
    security_logger = logging.getLogger("security")
    
    if security_logger.handlers:
        return security_logger
    
    # 安全日志文件
    security_log_file = settings.LOGS_DIR / "security.log"
    
    file_handler = logging.handlers.RotatingFileHandler(
        security_log_file,
        maxBytes=5 * 1024 * 1024,  # 5MB
        backupCount=5,
        encoding='utf-8'
    )
    
    formatter = logging.Formatter(
        "%(asctime)s - SECURITY - %(levelname)s - %(message)s"
    )
    file_handler.setFormatter(formatter)
    
    security_logger.addHandler(file_handler)
    security_logger.setLevel(logging.WARNING)
    security_logger.propagate = False
    
    return security_logger